package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.AppJwtUtil;
import io.jsonwebtoken.Jwts;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        //判断参数是否为null
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取前端传递的电话和密码
        String password = dto.getPassword();
        String phone = dto.getPhone();
        if (StringUtils.isEmpty(password)&&StringUtils.isEmpty(phone)){
            //游客登录
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> map=new HashMap<>();
            map.put("user",null);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
        //正常登录
        //校验手机号是否存在
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUser::getPhone,phone);
        ApUser apUser = apUserMapper.selectOne(wrapper);
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //比对密码
        String salt = apUser.getSalt();
        String passwordFromDB = apUser.getPassword();
        String md5passWord = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!md5passWord.equals(passwordFromDB)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //清空敏感信息
        apUser.setSalt("");
        apUser.setPassword("");
        String token = AppJwtUtil.getToken(apUser.getId().longValue());
        HashMap<String, Object> map = new HashMap<>();
        map.put("user",apUser);
        map.put("token",token);
        //返回结果
        return ResponseResult.okResult(map);
    }
}